package com.hs.hlw.credit.system.business.service.impl;

import com.hs.hlw.credit.system.business.dto.ResponseDto;
import com.hs.hlw.credit.system.business.service.SubmissionFormAttachmentService;
import com.hs.hlw.credit.system.common.enumeration.FileTypeEnum;
import com.hs.hlw.credit.system.common.util.DateTimeUtils;
import com.hs.hlw.credit.system.common.util.SftpUtil;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionFormAttachmentMapper;
import com.hs.hlw.credit.system.data.primary.mapper.SubmissionFormMapper;
import com.hs.hlw.credit.system.data.primary.model.SubmissionForm;
import com.hs.hlw.credit.system.data.primary.model.SubmissionFormAttachment;
import com.hs.hlw.credit.system.data.primary.model.SubmissionFormAttachmentExample;
import com.hualongdata.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * SubmissionFormAttachmentServiceImpl
 * @author zhb
 * @date 2018/11/28
 */
@Service
public class SubmissionFormAttachmentServiceImpl implements SubmissionFormAttachmentService {
    @Value("${sftp.server.sftpPath}")
    private String sftpPath;
    @Value("${sftp.server.host}")
    private String host;
    @Value("${sftp.server.port}")
    private Integer port;
    @Value("${sftp.server.username}")
    private String username;
    @Value("${sftp.server.password}")
    private String password;
    private @Autowired SubmissionFormAttachmentMapper submissionFormAttachmentMapper;
    private @Autowired SubmissionFormMapper submissionFormMapper;

    /**
     * 下载附件
     * @param id
     * @return
     */
    public void downloadAttachment(Integer id, HttpServletResponse response) {
        SubmissionFormAttachment attachment = submissionFormAttachmentMapper.selectByPrimaryKey(id);
        if (attachment == null) {
            throw new BusinessException("附件不存在");
        }

        String fileName = attachment.getSaveFileName();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(attachment.getUploadFileName(), "UTF-8"));

            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(sftpPath + "/" + attachment.getSavePath() + "/" + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            // TODO
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO
                }
            }
        }
    }

    /**
     * 排序上移
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto moveUp(Integer id) {
        SubmissionFormAttachment attachment = submissionFormAttachmentMapper.selectByPrimaryKey(id);
        if (attachment == null) {
            throw new BusinessException("附件不存在");
        }

        // 获取附件列表
        List<SubmissionFormAttachment> list = getAttachmentListByForm(attachment.getFormId());
        Integer index = null;
        for (int i = 0; i < list.size(); i++) {
            if (id.equals(list.get(i).getId())) {
                index = i;
                break;
            }
        }

        // 交换位置
        if (list.size() > 1 && index != null && index != 0) {
            SubmissionFormAttachment attachment2 = new SubmissionFormAttachment();
            attachment2.setId(attachment.getId());
            SubmissionFormAttachment attachment3 = list.get(index - 1);
            attachment2.setSort(attachment3.getSort());
            attachment3.setSort(attachment.getSort());
            submissionFormAttachmentMapper.updateByPrimaryKeySelective(attachment2);
            submissionFormAttachmentMapper.updateByPrimaryKeySelective(attachment3);
        }

        return new ResponseDto("操作成功");
    }

    /**
     * 排序下移
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto moveDown(Integer id) {
        SubmissionFormAttachment attachment = submissionFormAttachmentMapper.selectByPrimaryKey(id);
        if (attachment == null) {
            throw new BusinessException("附件不存在");
        }

        // 获取附件列表
        List<SubmissionFormAttachment> list = getAttachmentListByForm(attachment.getFormId());
        Integer index = null;
        for (int i = 0; i < list.size(); i++) {
            if (id.equals(list.get(i).getId())) {
                index = i;
                break;
            }
        }

        // 交换位置
        if (list.size() > 1 && index != null && index != (list.size() - 1)) {
            SubmissionFormAttachment attachment2 = new SubmissionFormAttachment();
            attachment2.setId(attachment.getId());
            SubmissionFormAttachment attachment3 = list.get(index + 1);
            attachment2.setSort(attachment3.getSort());
            attachment3.setSort(attachment.getSort());
            submissionFormAttachmentMapper.updateByPrimaryKeySelective(attachment2);
            submissionFormAttachmentMapper.updateByPrimaryKeySelective(attachment3);
        }

        return new ResponseDto("操作成功");
    }

    /**
     * 删除附件
     * @param id
     * @return
     */
    public ResponseDto delete(Integer id) {
        submissionFormAttachmentMapper.deleteByPrimaryKey(id);
        return new ResponseDto("操作成功");
    }

    /**
     * 附件列表
     * @param formId
     * @return
     */
    public ResponseDto list(Integer formId) {
        // 获取表单信息
        SubmissionForm submissionForm = submissionFormMapper.selectByPrimaryKey(formId);
        if (submissionForm == null) {
            throw new BusinessException("表单不存在");
        }

        List<SubmissionFormAttachment> attachmentList = getAttachmentListByForm(formId);
        Map<String, Object> data = new HashMap<>();
        String batchSubmissionExplain = submissionForm.getBatchSubmissionExplain();
        data.put("batchSubmissionExplain", batchSubmissionExplain != null ? batchSubmissionExplain : "");
        data.put("attachmentList", attachmentList);

        return new ResponseDto("查询成功", data);
    }

    /**
     * 附件列表
     * @param formId
     * @param batchSubmissionExplain
     * @return
     */
    public ResponseDto updateBatchSubmissionExplain(Integer formId, String batchSubmissionExplain) {
        // 获取表单信息
        SubmissionForm submissionForm = submissionFormMapper.selectByPrimaryKey(formId);
        if (submissionForm == null) {
            throw new BusinessException("表单不存在");
        }
        submissionForm.setBatchSubmissionExplain(batchSubmissionExplain);
        submissionFormMapper.updateByPrimaryKeySelective(submissionForm);
        return new ResponseDto("更新成功");
    }

    /**
     * 上传附件
     * @param formId
     * @param fileName
     * @param in
     * @return
     */
    public ResponseDto uploadAttachment(Integer formId, String fileName, InputStream in) {
        FileTypeEnum fileType = FileTypeEnum.getTypeByFileName(fileName);
        if (fileType == null) {
            throw new BusinessException("文件类型不支持");
        }

        // 获取表单信息
        SubmissionForm submissionForm = submissionFormMapper.selectByPrimaryKey(formId);
        if (submissionForm == null) {
            throw new BusinessException("表单不存在");
        }

        // 保存文件
        String dataStr = DateTimeUtils.dateToString(new Date(), DateTimeUtils.YYYY_MM_DD);
        SftpUtil.SftpDto sftpDto = new SftpUtil.SftpDto();
        sftpDto.setSftpPath(sftpPath);
        sftpDto.setHost(host);
        sftpDto.setPort(port);
        sftpDto.setUsername(username);
        sftpDto.setPassword(password);
        sftpDto.setSavePath(dataStr);
        sftpDto.setFileName(UUID.randomUUID().toString() + "." + fileType.value);
        sftpDto.setFileInputStream(in);
        SftpUtil.uploadFile(sftpDto);

        // 保存表单附件信息
        List<SubmissionFormAttachment> list = getAttachmentListByForm(formId);
        SubmissionFormAttachment submissionFormAttachment = new SubmissionFormAttachment();
        submissionFormAttachment.setFormId(formId);
        submissionFormAttachment.setSaveFileName(sftpDto.getFileName());
        submissionFormAttachment.setUploadFileName(fileName);
        submissionFormAttachment.setSavePath(dataStr);
        submissionFormAttachment.setCreateTime(new Date());
        if (list == null || list.isEmpty()) {
            submissionFormAttachment.setSort(1);
        } else {
            Integer sort = list.get(list.size() - 1).getSort();
            submissionFormAttachment.setSort(sort == null ? null : sort + 1);
        }
        submissionFormAttachmentMapper.insertSelective(submissionFormAttachment);

        return new ResponseDto("上传成功");
    }

    /**
     * 获取表单附件列表
     * @param formId
     * @return
     */
    private List<SubmissionFormAttachment> getAttachmentListByForm(Integer formId) {
        SubmissionFormAttachmentExample example = new SubmissionFormAttachmentExample();
        SubmissionFormAttachmentExample.Criteria criteria = example.createCriteria();
        criteria.andFormIdEqualTo(formId);
        example.setOrderByClause("sort asc");
        List<SubmissionFormAttachment> list = submissionFormAttachmentMapper.selectByExample(example);
        return list;
    }
}